# -*- coding: utf-8 -*-

'''
连接linux 2018年11月16日09:49:14
'''
import paramiko
import os
import time

host = "192.168.0.188";
user_name = "root";
password = "188dongdong";


def createConnection():
    ssh = paramiko.SSHClient()
    # 自动认证
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(host, 22, user_name, password);
    return ssh;


if __name__ == '__main__':
    print("start");
    ssh = createConnection();

    print("shutdown tomcat");
    stdin, stdout, stderr = ssh.exec_command(
        ' export JAVA_HOME=/usr/local/java/jdk1.8.0_141 && export JRE_HOME=/usr/local/java/jdk1.8.0_141/jre && /root/app/apache-tomcat-8.5.20/bin/shutdown.sh');
    print(stdout.readlines());

    time.sleep(5);
    # 多个命令用';'分隔。
    # 单独'cd'执行切换目录会失效，因为exec_command是会话模式，
    # 执行成功会话结束，会回到初始目录，导致切换目录无效，可以多个命令执行解决。
    stdin, stdout, stderr = ssh.exec_command('ps -ef | grep tomcat |grep -v \'grep\' | awk \'{print $2}\'');

    for procId in stdout.readlines():
        # 打印命令执行情况
        print("kill -15 " + procId);

        stdin, stdout, stderr = ssh.exec_command('kill -15 ' + procId)
        print(stdout.readlines());

    print(" remove ROOT and ROOT.war");

    tomcat_path = "/root/app/apache-tomcat-8.5.20/webapps/";
    stdin, stdout, stderr = ssh.exec_command('rm -rf ' + tomcat_path + 'ROOT');
    print(stdout.readlines());
    stdin, stdout, stderr = ssh.exec_command('rm -rf ' + tomcat_path + 'ROOT.war');
    print(stdout.readlines());

    print("put file");
    target_file = "D:/work/newFramework/east-meeting-chess-admin/trunk/east-meeting-chess-server/server-admin/target/ROOT.war";

    # 实例化一个trans对象# 实例化一个transport对象
    trans = paramiko.Transport((host, 22))
    # 建立连接
    trans.connect(username=user_name, password=password)

    # 实例化一个 sftp对象,指定连接的通道
    sftp = paramiko.SFTPClient.from_transport(trans)
    # 发送文件
    sftp.put(localpath=target_file, remotepath=os.path.join(tomcat_path, "ROOT.war"));
    # 下载文件
    # sftp.get(remotepath, localpath)
    trans.close()

    print("start tomcat");

    stdin, stdout, stderr = ssh.exec_command(' export JAVA_HOME=/usr/local/java/jdk1.8.0_141 && export JRE_HOME=/usr/local/java/jdk1.8.0_141/jre && /root/app/apache-tomcat-8.5.20/bin/startup.sh');
    print(stdout.readlines());
    ssh.close();
    print("end ");
    random_input = input(" 请输入任意字符结束. ");
